/*
 * This javascript is part of YAES.
 */

function search_show(model)
{
  var dialog = $('#searchDialog');
  dialog.attr('title', dialog.data('titles')[model]);
  
  var headers = dialog.data('headers');
  if (headers[model] == undefined) {
    console.error('Headers for model ' + model + ' is not defined!');
    return;
  }
  var sort_configuration = dialog.data('sort_configuration');
  if (sort_configuration[model] == undefined) {
    console.error('Sort configuration for model ' + model + ' is not defined!');
    return;
  }
  sort_configuration = sort_configuration[model];
  
  dialog.data('model', model);
  /* Set the header */
  dialog.find('div.results table thead').html('<th>' + headers[model].join('</th><th>') + '</th>');
  
  /* Set up sorting buttons */
  dialog.find('thead th').each(function(i, item) {
    item = $(item);
    if (i == 0)
      item.addClass('sorting asc');
    
    item.data('field', sort_configuration[i])
    
    item.click(function(e) {
      var header = $(e.currentTarget);
      
      var sort = 'asc';
      if (header.hasClass('asc'))
        sort = 'desc';
      
      header.parents('#searchDialog thead').find('th').removeClass('sorting').removeClass('desc').removeClass('asc');
      header.addClass('sorting ' + sort);
      
      dialog.data('no_more_itemss', false);
      dialog.data('last_item', 0);
      $('#searchDialog tbody').html('');
      
      dialog.data('queryCb')(e);
    });
  });
  
  dialog.dialog({
    width: 700,
    modal: 'true'
  });
}

function search_hide(model)
{
  $('#searchDialog').dialog('close');
}

function search_setcb(model, cb, fetch_data) {
  if (fetch_data == undefined)
    fetch_data = false;
  
  var dialog = $('#searchDialog');
  var cbs = dialog.data('callbacks');
  if (cbs == undefined)
    cbs = {};
  
  cbs[model] = {
    'cb': cb,
    'fetch_data': fetch_data
  };
  dialog.data('callbacks', cbs);
}

/* Insert dialog */
$(document).ready(function() {
  /* Create the dialog */
  var dialog = $('<div id="searchDialog" style="display:none;"></div>');
  
  /* Create the form */
  var form = $('<p><label>Iskalni pojem:</label>&nbsp;<input type="text" class="search_query" /><button>Išči</button></p>');
  dialog.append(form);
  
  /* Create space for results */
  var results = $('<br style="clear: both" /><div class="results" style="max-height: 300px; overflow-y: auto;"></div>');
  dialog.append(results);
  results.html('<table class="ajax_search_result"><thead></thead><tbody></tbody></table>');
  
  /* Results headers for specific model */
  dialog.data('headers', {
    'student': ['Vpisna številka', 'Priimek', 'Ime'],
    'professor': ['Šifra', 'Priimek', 'Ime']
  });
  /* Field ordering */
  dialog.data('sort_configuration', {
    'student': ['enrollment_number', 'user__last_name', 'user__first_name'],
    'professor': ['code', 'user__last_name', 'user__first_name']
  });
  /* Row configuration */
  dialog.data('rows', {
    'student': ['pk', 'fields.user.fields.last_name', 'fields.user.fields.first_name'],
    'professor': ['pk', 'fields.user.fields.last_name', 'fields.user.fields.first_name']
  });
  /* Titles */
  dialog.data('titles', {
    'student': 'Iskalnik študenta',
    'professor': 'Iskalnik profesorja'
  });
  
  /* Add search logic */
  dialog.data('queryCb', function(e) {
    var dialog = $('#searchDialog');
    var query = dialog.find('input').val();
    var model = dialog.data('model');
    
    if (dialog.data('is_loading') == true)
      return;
    dialog.data('is_loading', true);
    
    /* Notify the user that search is in progress */
    var row = $('<tr></tr>');
    row.addClass('loading');
    row.html('<td colspan="3">Iskanje poteka</td>');
    dialog.find('tbody').append(row);
    
    /* Create ordering stuff */
    var order = {
      'field': undefined,
      'order': undefined
    };
    dialog.find('th').each(function(i, item) {
      item = $(item);
      if (item.hasClass('sorting')) {
        order.field = item.data('field');
        if (item.hasClass('desc')) {
          order.order = 'desc';
        } else {
          order.order = 'asc';
        }
        
        return false;
      }
    });
    
    /* Send a request */
    $.post('/search/' + model + '/', {
      query: query,
      last_item: dialog.data('last_item'),
      sorting_field: order.field,
      sorting_order: order.order
    }, function(data) {
      var dialog = $('#searchDialog');
      var resultsList = $('#searchDialog div.results');
      var model = dialog.data('model');
      var cb = dialog.data('callbacks')[model];
      if (cb == undefined) {
        cb = {
          'cb': function() {},
           'fetch_data': false
        };
        console.log(dialog.data('callbacks'));
        console.error('Model not defined!');
      }
      
      var wrapper;
      if (cb.fetch_data == true) {
        /* Fetch aditional data */
        wrapper = function(c, st) { return function() {
          /* Some waiting message? */
          $.get('/get/' + model + '/' + st.pk + '/', {}, (function(c) { return function (data) {
            if (data.length > 0) {
              c(data[0]);
            } else {
              /* Some error reporting? */
            }
          };})(c));
        };};
      } else {
        /* Use the data given to you... :D */
        wrapper = function(c, st) { return function() {
          c(st);
        };};
      }
      
      if (data.length > 0) {
        $.each(data, function(i, student) {
          var row = $('<tr></tr>');
          var row_configuration = dialog.data('rows')[model];
          if (row_configuration == undefined) {
            console.error('Rows configuration for model ' + model + ' is not defined!');
            return false;
          }
          
          /* Fill up data into row */
          $.each(row_configuration, function(j, item) {
            var cell_data = student;
            $.each(item.split('.'), function(k, field) {
              cell_data = cell_data[field];
            });
            
            var cell = $('<td></td>');
            cell.text(cell_data);
            row.append(cell);
          });
          
          /* Append the row */
          $('#searchDialog div.results tbody').append(row);
          
          /* Assign some data */
          row.data('student', student);
          if (cb.cb != undefined)
            row.click(wrapper(cb.cb, student));
        });
      } else if ($('#searchDialog div.results tbody').children('tr').length < 2) {
        var row = $('<tr></tr>');
        row.addClass('empty');
        var msg = $('<td colspan="3"></td>');
        row.append(msg);
        msg.text('Iskanje ni vrnilo rezultatov');
        
        $('#searchDialog div.results tbody').append(row);
      } else {
        dialog.data('no_more_itemss', true);
      }
      
      /* Update last index */
      dialog.data('last_item', dialog.data('last_item') + data.length);
      dialog.find('tr.loading').remove();
      dialog.data('is_loading', false);
    });
  });
  
  form.find('button').click(function(e) {
    var dialog = $('#searchDialog');
    if (dialog.data('is_loading') == false) {
       dialog.data('no_more_itemss', false);
      dialog.data('last_item', 0);
      $('#searchDialog tbody').html('');
      e.preventDefault();
      dialog.data('queryCb')(e);
    }
  });
  form.find('input').keyup(function(e) {
    var dialog = $('#searchDialog');
    if (e.keyCode == '13' && dialog.data('is_loading') == false) {
      dialog.data('no_more_itemss', false);
      dialog.data('last_item', 0);
      $('#searchDialog tbody').html('');
      e.preventDefault();
      dialog.data('queryCb')(e);
    }
  });
  results.scroll(function(e) {
    var results = $(e.currentTarget);
    
    if ($('#searchDialog').data('no_more_itemss') == false && results.scrollTop() > results.children('table').height() - 500)
      dialog.data('queryCb')(e);
  });
  
  /* Add dialog to document */
  $(document.body).append(dialog);
  
  /* Set starting index */
  dialog.data('last_item', 0);
  dialog.data('is_loading', false);
  dialog.data('no_more_itemss', false);
});
